package com.framework;

import java.lang.reflect.Field;
import java.util.regex.Pattern;

// RegexRule实现
class RegexRule implements ValidationRule {
    private final String field;
    private final Pattern pattern;
    private final String errorMessage;
    
    public RegexRule(String field, String regex, String errorMessage) {
        this.field = field;
        this.pattern = Pattern.compile(regex);
        this.errorMessage = errorMessage;
    }
    
    @Override
    public ValidationResult validate(Object object) {
        try {
            Field f = object.getClass().getDeclaredField(field);
            f.setAccessible(true);
            Object value = f.get(object);
            
            if (value == null || !(value instanceof String)) {
                return ValidationResult.valid(); // 非字符串由其他规则处理
            }
            
            String str = (String) value;
            if (!pattern.matcher(str).matches()) {
                return ValidationResult.invalid(field, "REGEX_FAILED", field + errorMessage);
            }
            
            return ValidationResult.valid();
        } catch (Exception e) {
            return ValidationResult.invalid(field, "SYSTEM_ERROR", "系统错误: " + e.getMessage());
        }
    }
}